package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entity.pojo.WrUser;
import com.entity.vo.LoginResult;
import com.entity.vo.UserVo;
import com.mapper.WrUserMapper;
import com.service.UserService;
import com.utils.JwtUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service("userService")
@Log4j2
public class UserServiceImp implements UserService {

    @Resource
    private WrUserMapper userMapper;

    @Override
    public LoginResult userLogin(WrUser user) {
        WrUser result = userMapper.selectOne(new QueryWrapper<WrUser>().eq("username", user.getUsername()));
        if (result == null) {
            return null;
        }
        if (user.getPassword().equals(result.getPassword())) {
            return new LoginResult().setUser(result).setToken(JwtUtil.createToken(user.getUsername()));
        } else {
            return null;
        }
    }

    @Override
    public String getRole(WrUser user) {
        return userMapper.getUserRole(user);
    }

    @Override
    public List<UserVo> listUser() {
        return userMapper.listUser();
    }

    @Override
    public int insertUser(WrUser user) {
        List<WrUser> list = userMapper.selectList(new QueryWrapper<WrUser>().eq("username", user.getUsername()));
        if (list.isEmpty()) {
            LocalDateTime localDateTime = LocalDateTime.now();
            System.out.println(localDateTime);
            return userMapper.insert(user.setCreateTime(localDateTime));
        } else {
            return -1;
        }
    }

    @Override
    public int deleteUser(int id) {
        return userMapper.updateById(userMapper.selectById(id).setDeleted(1));
    }

    @Override
    public int resetUserPassword(int id) {
        return userMapper.updateById(new WrUser().setId(id).setPassword("123456").setUpdateTime(LocalDateTime.now()));
    }

    @Override
    public int updateUser(WrUser user) {
        return userMapper.updateById(user);
    }
}
